//
//  LoginViewController.m
//  Netinhand
//
//  Created by Zhou, Shaolin on 11/4/11.
//  Copyright (c) 2011 Microstrategy. All rights reserved.
//

//登录管理
#import "LoginViewController.h"
#import "UserAccount.h"
#import <QuartzCore/QuartzCore.h>
#import "JsonFileIO.h"
#import "AppDelegate.h"
#import "Utility.h"
#import "XmlReader.h"
#import "JSON.h"
#import "MBProgressHUD.h"
#import "settingViewController.h"

#define CHECK_VERSION_ALERT 2
#define CHECK_RESULT_ALERT 3

@interface LoginViewController(Private)  
- (void)setLoading:(BOOL)showOrNot withText:(NSString*)loadingString;
- (void)updating:(BOOL)showOrNot;
- (void)checkVersion;
-(void)reCheckVersion;
@end

@implementation LoginViewController
//@synthesize delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) {
            self.edgesForExtendedLayout = UIRectEdgeNone;
        }

        // Custom initialization
    }
    return self;
}
/*
-(id)initWithDelegate:(UIViewController<LoginProtocol>*)theDelegate
{
    if (self = [super init]) {
        self.delegate = theDelegate;
    }
    return self;
}*/


#pragma mark - View lifecycle
//初始化界面上的控件的字符串，状态
- (void)viewDidLoad{
    [super viewDidLoad];
    self.title=@"云报销";
    self.view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"Default.png"]];
    //self.view.backgroundColor=[UIColor  colorWithRed:11.0f/255.0f green:49.0f/255.0f blue:62.0f/255.0f alpha:1.0];
    userNameView.layer.cornerRadius = 5.0;
    passwordView.layer.cornerRadius = 5.0;
    JsonFileIO* fileIO = [[[JsonFileIO alloc] initFileName:@"pwdSaved.plist"] autorelease];
    NSDictionary* dict = [fileIO readDataToDict];
    if ([[dict objectForKey:@"checked"] boolValue]) {
        NSString* userName = [dict objectForKey:@"username"];
        NSString* passwrod = [dict objectForKey:@"passwrod"];
        userNameField.text = userName;
        passwordField.text = passwrod;
        [checkBox setSelected:YES];
    }
    else
    {
        [checkBox setSelected:NO];
    }
    
    UIBarButtonItem *rightButton=[[UIBarButtonItem alloc] initWithCustomView:[self customButtom:100 withFrame:CGRectMake(10, 0, 50, 30) action:@selector(settingAction:) normalImage:@"big_setting.png" lightedImage:@"big_setting.png" title:@""]];
    rightButton.style = UIBarButtonItemStylePlain;
    self.navigationItem.rightBarButtonItem=rightButton;
    [rightButton release];
    
}

-(IBAction)settingAction:(id)sender{
    settingViewController *set=[[settingViewController alloc] init];
    [self.navigationController  pushViewController:set animated:YES];
    [set release];

}

-(IBAction)checkRememberPWD:(id)sender{
    UIButton* checkBtn = (UIButton*)sender;
    BOOL bState = [checkBtn isSelected];
    [checkBtn setSelected:!bState];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
    NSString *ini=[userdefault objectForKey:@"sysParams"];
    NSString *url=[userdefault objectForKey:@"kServiceURL"];
    if (ini==nil||[ini isEqualToString:@""]||url==nil||[url isEqualToString:@""]) {
        [self settingAction:nil];
    }
    NSString *userName=[userdefault objectForKey:@"userName"];
    if(nil!=userName&&![@"" isEqualToString:userName]){
        userNameField.text=userName;
    }else {
        [userNameField becomeFirstResponder];
    }
    
}

-(IBAction)loginAction:(id)sender{
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
    NSString *ini=[userdefault objectForKey:@"sysParams"];
    NSString *url=[userdefault objectForKey:@"kServiceURL"];
    if (ini==nil||[ini isEqualToString:@""]||url==nil||[url isEqualToString:@""]) {
        [self settingAction:nil];
    }

    
    [MBProgressHUD showHUDAddedTo:self.view animated:NO];
    [userNameField resignFirstResponder];
    [passwordField resignFirstResponder];
    NSString* userName = userNameField.text;
    NSString* passwrod = passwordField.text;
    userName = [userName stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
    passwrod = [passwrod stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
    if (passwrod == nil) {
        passwrod = @"";
    }
    NSString* pwd = [Utility encode:passwrod];
    [userNameField  resignFirstResponder];
    [passwordField  resignFirstResponder];
    if (requestManager == nil) {
        requestManager = [[UrlRequest alloc] initWithDelegate:self requestSelector:@selector(parseReceivedData:) errorSelector:@selector(errorCallback)];
    }
    [requestManager login:userName pwd:pwd];
    [userdefault  setValue:userName forKey:@"userName"];
    [userdefault synchronize];
   // [requestManager requestToCheckList];
}

-(void)parseReceivedData:(id)data{
   if (data==nil||[data isEqualToString:@""]) {
            NSLog(@"login receivedString=%@",@"空");
            [ MBProgressHUD  hideHUDForView:self.view animated:NO];
            return;
    }
    NSError *error;
   NSDictionary *resultData=[XmlReader dictionaryForXMLString:data error:&error];
    NSDictionary *userPasswordDict=[[[[[[[resultData  objectForKey:@"soap:Envelope"] objectForKey:@"soap:Body"] objectForKey:@"GetDataSetSqlResponse"] objectForKey:@"GetDataSetSqlResult"] objectForKey:@"diffgr:diffgram"] objectForKey:@"NewDataSet"] objectForKey:@"Table"];
    NSString *USER_ID=[[userPasswordDict objectForKey:@"USER_ID"] objectForKey:@"text"];
    NSString *USER_NAME=[[userPasswordDict objectForKey:@"USER_NAME"] objectForKey:@"text"];
    NSUserDefaults *userDefault=[NSUserDefaults standardUserDefaults];
    if (USER_ID!=nil&&![@"" isEqualToString:USER_ID]) {
        [userDefault setValue:USER_ID forKey:@"USER_ID"];
        [userDefault setValue:USER_NAME forKey:@"USER_NAME"];
        if (requestManager == nil) {
            [requestManager release];
            requestManager=nil;
        }
        requestManager = [[UrlRequest alloc] initWithDelegate:self requestSelector:@selector(parseReceivedData_ship:) errorSelector:@selector(errorCallback)];
        [requestManager requestToHeadShip:USER_ID];
   
    }else {
        [MBProgressHUD  hideHUDForView:self.view animated:NO];
        UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"提醒" message:@"用户名或密码不正确" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
        [alertView  release];
    }
    
    
}

-(void)parseReceivedData_ship:(id)data{
    if (data==nil||[data isEqualToString:@""]) {
        NSLog(@"login_shop receivedString=%@",@"空");
        [ MBProgressHUD  hideHUDForView:self.view animated:NO];
        return;
    }
    NSError *error;
    NSDictionary *resultData=[XmlReader dictionaryForXMLString:data error:&error];
    id array=[[[[[[[resultData  objectForKey:@"soap:Envelope"] objectForKey:@"soap:Body"] objectForKey:@"GetDataSetSqlResponse"] objectForKey:@"GetDataSetSqlResult"] objectForKey:@"diffgr:diffgram"] objectForKey:@"NewDataSet"] objectForKey:@"Table"];
    NSString *headShip=@"";
    if ([[array JSONRepresentation] hasPrefix:@"{"]) {
        headShip=[[array objectForKey:@"USERH_HEADSHIP"] objectForKey:@"text"];
    }else {
        for (NSDictionary *temp in array) {
            if (headShip.length<1) {
                headShip=[[temp objectForKey:@"USERH_HEADSHIP"] objectForKey:@"text"];
            }else {
                headShip=[NSString stringWithFormat:@"%@,%@",headShip,[[temp objectForKey:@"USERH_HEADSHIP"] objectForKey:@"text"]];
            }
        }
        
    }
       NSUserDefaults *userDefault=[NSUserDefaults standardUserDefaults];
            [userDefault setValue:headShip forKey:@"USERH_HEADSHIP"];
        [userDefault synchronize];
    [MBProgressHUD  hideHUDForView:self.view animated:NO];
    AppDelegate *appDelegate=[UIApplication sharedApplication].delegate;
    [appDelegate  popLoginViewController];
    //[appDelegate.tabbar dismissModalViewControllerAnimated:NO];
    //[delegate loginSuccess];
    
}

-(void)errorCallback{
    [MBProgressHUD  hideHUDForView:self.view animated:NO];
    NSString* okTitle = @"提醒";
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"网路异常" delegate:nil cancelButtonTitle:okTitle otherButtonTitles:nil];
    [alert show];
    [alert release];
}



- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == userNameField) {
        NSUInteger newLength = [textField.text length] + [string length] - range.length;
        return (newLength > 12) ? NO : YES;
    }
    else
    {
        NSUInteger newLength = [textField.text length] + [string length] - range.length;
        return (newLength > 16) ? NO : YES;
    }
}



- (void)viewDidUnload
{
    [super viewDidUnload];
    [userNameField release]; userNameField = nil;
    [passwordField release]; passwordField = nil;
    [userNameView release]; userNameView = nil;
    [passwordView release]; passwordView = nil;
    [checkBox release]; checkBox = nil;
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


- (UIButton*) customButtom:(NSUInteger)numberOfTag withFrame:(CGRect)frame action:(SEL)action normalImage:(NSString*)normalImage lightedImage:(NSString*)lightedImage  title:(NSString *)title{
    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    button.tag=numberOfTag;
    button.backgroundColor=[UIColor clearColor];
    UIImage *normal_Image=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:normalImage ofType:nil]];
    UIImage *lighted_Image=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:lightedImage ofType:nil]];
    //[button setTitle:title forState:UIControlStateNormal];
    [button setImage:normal_Image forState:UIControlStateNormal];
    [button setImage:lighted_Image forState:UIControlStateHighlighted];
    [button setImage:lighted_Image forState:UIControlStateSelected];
    button.adjustsImageWhenHighlighted = NO;
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    return button;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation==UIDeviceOrientationPortrait);
}
- (BOOL)shouldAutorotate{
    return NO;
}
- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskAllButUpsideDown;
}

-(void)dealloc{
    [userNameField release];
    [passwordField release];
    [userNameView release];
    [passwordView release];
    [checkBox release];
    [requestManager  release];
   // [delegate release];
    
    [super dealloc];
}


@end
